﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using PddHelper.Api;
using PddHelper.Models;

namespace WebApiExtend
{
    /// <summary>
    /// 结果过滤器
    /// </summary>
    public class ResultFilter : Attribute, IResultFilter
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public void OnResultExecuted(ResultExecutedContext context)
        {
            // 在结果执行之后调用的操作...
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public void OnResultExecuting(ResultExecutingContext context)
        {
            //var isReturnDefaultValue = context.ActionDescriptor.EndpointMetadata.Any(ex => ex.ToString() == typeof(ReturnDefaultValue).ToString());//不改变默认结构

            //// 在结果执行之前调用的一系列操作
            //object result;
            //if (isReturnDefaultValue)
            //{
            //    result = ((ObjectResult)context.Result).Value;
            //}
            //else if (((ObjectResult)context.Result).Value != null && ((ObjectResult)context.Result).Value.GetType().Name == "ApiResult`1")
            //{
            //    result = ((ObjectResult)context.Result).Value;
            //}
            //else
            //{
            //    result = new ApiResult<object> { Code = ApiStatusCode.OK, Msg = "SUCCESS", Data = ((ObjectResult)context.Result).Value };
            //}

            //if (((ObjectResult)context.Result).StatusCode != null && ((ObjectResult)context.Result).StatusCode != 200)
            //{
            //    var err = ""; string ls = "";
            //    foreach (var item in ((ValidationProblemDetails)((ObjectResult)context.Result).Value).Errors)
            //    {
            //        err += ls + string.Join(",", item.Value);
            //        ls = "\n";
            //    }
            //    result = new ApiResult<object> { Code = ApiStatusCode.InternalServerError, Msg = err };
            //}

            //IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
            //timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
            //context.Result = new ContentResult
            //{
            //    StatusCode = ((ObjectResult)context.Result).StatusCode,
            //    ContentType = "application/json;charset=utf-8",
            //    Content = isReturnDefaultValue ? result.ToString() : JsonConvert.SerializeObject(result, Newtonsoft.Json.Formatting.Indented, timeFormat)
            //    //支持表格下载
            //};
        }
    }
}
